package top.codedance.iotp.tools.serverTool.ui;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.util.SystemUtil;
import top.codedance.iotp.tools.serverTool.ServerToolApplication;
import top.codedance.iotp.tools.terminal.ui.ConnectionManager;

import javax.swing.*;
import java.net.URL;
import java.util.Map;
import java.util.Set;

/**
 *
 * @author xuedianfu
 */
public class SelectConnectFrame extends javax.swing.JDialog {
    private MainFrame mf;
    private DefaultComboBoxModel<String> dlmB;
    public JSONObject connectData = new JSONObject();
    private JSONObject currentConnectionParam;

    /**
     * Creates new form SelectConnectFrame
     */
    public SelectConnectFrame(MainFrame mf) {
        super(mf, true);
        this.mf = mf;
        initComponents();
        URL url = Thread.currentThread().getContextClassLoader().getResource("logo.gif");
        ImageIcon icon = new ImageIcon(url);
        setIconImage(icon.getImage());
        setLocationRelativeTo(this.mf.getShellFrame());
        setTitle("代码飞舞采控系统-选取SERVER");

        initList();
    }

    public void initList(){
        dlmB = new DefaultComboBoxModel<>();
        this.jcb_connect.setModel(dlmB);
        initListData();
    }

    public void initListData(){
        String s = SystemUtil.readTempFile(ConnectionManager.CONNECTION_TMP_FILENAME);
        if(null != s && !s.isEmpty()) {
            connectData = JSON.parseObject(s);
            dlmB.removeAllElements();
            Set<Map.Entry<String, Object>> entries = connectData.entrySet();
            JSONObject jo;
            for (Map.Entry<String, Object> entry : entries) {
                jo = (JSONObject)entry.getValue();
                if(jo.containsKey("type") && jo.getString("type").equals("http")) {
                    dlmB.addElement(entry.getKey());
                }
            }
            this.jcb_connect.repaint();
            getConnect();
        }
    }

    private JSONObject getConnect(){
        String key = (String)jcb_connect.getSelectedItem();
        currentConnectionParam = this.connectData.getJSONObject(key);
        return currentConnectionParam;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jcb_connect = new javax.swing.JComboBox<>();
        jb_ok = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        jLabel1.setText("选取Server：");

        jb_ok.setText("确定");
        jb_ok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_okActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jcb_connect, 0, 320, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jb_ok)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jcb_connect, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jb_ok))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jb_okActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_okActionPerformed
        JSONObject connect = getConnect();
        if(connect != null) {
            ServerToolApplication.serverConf.setServerHost(connect.getString("url"));
            ServerToolApplication.serverConf.setUsername(connect.getString("username"));
            ServerToolApplication.serverConf.setPassword(connect.getString("password"));
            mf.setStatus("<html><body><p align=\"center\"><span style=\"color: #FFFFFF;\">当前选取的连接：<br />[</span><span style=\"color: #FF6666;\">" + connect.getString("name") + "</span><span style=\"color: #FFFFFF;\">]</span></p></body></html>");
            setVisible(false);
        }else{
            JOptionPane.showMessageDialog(rootPane, "连接不能为空。");
        }
    }//GEN-LAST:event_jb_okActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JButton jb_ok;
    private javax.swing.JComboBox<String> jcb_connect;
    // End of variables declaration//GEN-END:variables
}
